<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/mineBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="绩效考核" :showBack="true"></cusHeaderVue>
		<view class="screenBox" :style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`}">
			<view class="tabBox">
				<view class="tabLi" :class="tabIndex==0?'tabLiA':''" @click="chooseTab(0)">
					未打分<text>{{ unScoredCount }}</text>
				</view>
				<view style="width: 100rpx;">
				</view>
				<view class="tabLi" :class="tabIndex==1?'tabLiA':''" @click="chooseTab(1)">
					已打分<text>{{ scoredCount }}</text>
				</view>
			</view>
			<view class="screenTime" @click="openDatePicker">
				{{ currentDate }}
				<image src="/static/mine/xiala.png" mode=""></image>
			</view>
		</view>
		<MonthPickerPopup ref="monthPickerRef" @confirm="handleDateConfirm" @cancel="handleDateCancel" />
		<scroll-view scroll-y="true" :style="{height: `calc(100vh - ${scrollerHeight} - 90rpx - 75rpx`}">
			<view class="contBox">
				<view v-if="loading" class="loading">加载中...</view>
				<view v-else-if="salaryData.length === 0" class="empty">暂无数据</view>
				<view class="contList" v-if="tabIndex==0 && !loading" v-for="(item,index) in salaryData.filter(item => !item.score)" :key="item.id || index"
					@click="toUrl(`/pages/mine/salesRepresentative?id=${item.uid}`)">
					<view class="contTop">
						<view class="contPerson">
							<view class="contPhoto">
								<image :src="item.avatar" mode="aspectFill"></image>
							</view>
							<view class="contTopName">
												{{ item.name || '未知姓名' }}
							</view>
						</view>
						<view class="contTopRight" @click.stop="mark(item)">
							去打分
						</view>
					</view>
				</view>

				<view class="contList" v-if="tabIndex==1 && !loading" v-for="(item,index) in salaryData.filter(item => item.score)" :key="item.id || index"
					@click="toUrl(`/pages/mine/salesRepresentative?id=${item.uid}`)">
					<view class="contYdf">
						<image :src="item.avatar" mode="aspectFill"></image>
						<!-- <image src="/static/logo.png" mode=""></image> -->
					</view>
					<view class="contYdfRight">
						<view class="contYdfRightTop">
							<view class="contYdfRightName">
												{{ item.name || '未知姓名' }}
										</view>
										<view class="contYdfRightNum">
											{{ item.score || '0' }}分
										</view>
						</view>
						<view class="contYdfRightText">
							<image src="/static/mine/pingyu.png" mode=""></image>
							<view class="contYdfRightTextCont">
												评语: {{ item.comment || '暂无评语' }}
							</view>
						</view>
					</view>
				</view>

			</view>
		</scroll-view>
		<u-popup :safeAreaInsetBottom="false" :show="show" :round="13" mode="center" @close="close" @open="open">
			<view class="popupBox">
			<view class="popupTit">
				正在给【{{ selectedItem?.name || '未知人员' }}】打分
			</view>
			<view class="popupLi">
				<view class="popupName">
					表现打分
				</view>
				<view class="popupInpt">
					<input type="number" v-model="scoreValue" class="popupInptText" placeholder="请输入分数(0-100)" style="text-align: center;" />
				</view>
				<view class="popupTip">
					100分制
				</view>
			</view>
			<view class="popupLi" style="align-items: initial;">
				<view class="popupName">
					表现评语
				</view>
				<view class="popupTextarea">
					<textarea placeholder="请输入评语" v-model="commentValue"></textarea>
				</view>
			</view>
			
			<view class="popupBtn" @click="confirmScore">
				确认打分
			</view>
		</view>
		</u-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		ref,
		computed
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import MonthPickerPopup from '@/components/MonthPickerPopup.vue';
	import { listSalary, makeScoreOperation } from '@/api/interface.js';
	
	// 响应式数据
const scrollerHeight = ref('');
const tabIndex = ref(0);
const show = ref(false);
const monthPickerRef = ref(null);
const currentDate = ref('');
const currentMonthStr = ref('');
const unScoredCount = ref(0);
const scoredCount = ref(0);
const salaryData = ref([]);
const loading = ref(false);
const selectedItem = ref(null);
const scoreValue = ref('');
const commentValue = ref('');

	// 获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}
	
	// 初始化当前日期
	const initCurrentDate = () => {
		// 默认上一个月
		const now = new Date();
		now.setMonth(now.getMonth() - 1);
		const year = now.getFullYear();
		const month = now.getMonth() + 1; // setMonth 已调整到上个月，这里 +1 为自然月
		currentDate.value = `${year}年${month}月`;
		currentMonthStr.value = `${year}-${month.toString().padStart(2, '0')}`;
	}
	
	// 获取薪资列表数据
const getSalaryData = async (monthStr = '') => {
	loading.value = true;
	try {
		const params = {};
		if (monthStr) {
			params.monthStr = monthStr;
		}
		const res = await listSalary(params);
		if (res.code === 0) {
			// 处理返回的数据，按照新的格式（ddf未打分，ydf已打分）
			const unScoredData = (res.data.ddf || []).map(item => ({
				...item,
				name: item.nickname || item.name || '未知姓名',
				avatar: item.avatar || item.avatar || '',
				score: null // 未打分为空
			}));
			const scoredData = (res.data.ydf || []).map(item => ({
				...item,
				name: item.nickname || item.name || '未知姓名',
				score: item.userScore || item.score || 0,
				avatar: item.avatar || item.avatar || '',
				comment: item.evaluateStr || item.comment || '暂无评语'
			}));
			// 合并数据
			salaryData.value = [...unScoredData, ...scoredData];
			// 更新统计数据
			unScoredCount.value = unScoredData.length;
			scoredCount.value = scoredData.length;
		} else {
			uni.showToast({
				title: res.msg || '获取数据失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('获取薪资数据失败:', error);
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		});
	} finally {
		loading.value = false;
		// 停止下拉刷新
		uni.stopPullDownRefresh();
	}
}
	
	// 打开日期选择器
	const openDatePicker = () => {
		monthPickerRef.value.open();
	}
	
	// 处理日期确认
	const handleDateConfirm = (dateStr) => {
		currentDate.value = dateStr;
		// 格式转换："2025年5月" -> "2025-05"
		const [year, month] = dateStr.match(/\d+/g);
		currentMonthStr.value = `${year}-${month.toString().padStart(2, '0')}`;
		// 调用接口获取数据
		getSalaryData(currentMonthStr.value);
	}
	
	// 处理日期取消
	const handleDateCancel = () => {
		// 取消操作，无需处理
	}
	
	// 选择标签页
const chooseTab = (index) => {
	tabIndex.value = index;
	// 切换tab时调用接口获取数据
	getSalaryData(currentMonthStr.value);
}
	
	// 关闭弹窗
const close = () =>{
	show.value = false
	// 重置表单
	scoreValue.value = '';
	commentValue.value = '';
}

// 确认打分
const confirmScore = async () => {
	// 验证分数是否有效
	const score = parseInt(scoreValue.value);
	if (!selectedItem.value || !scoreValue.value || isNaN(score) || score < 0 || score > 100) {
		uni.showToast({
			title: '请输入有效的分数(0-100)',
			icon: 'none'
		});
		return;
	}
	
	try {
		uni.showLoading({ title: '提交中' });
		const params = {
			id: selectedItem.value.id.toString(),
			score: scoreValue.value,
			pzStr: commentValue.value
		};
		
		const res = await makeScoreOperation(params);
		
		if (res.code === 0) {
			uni.showToast({
				title: '打分成功',
				icon: 'success'
			});
			close();
			// 重新获取数据
			getSalaryData(currentMonthStr.value);
		} else {
			uni.showToast({
				title: res.msg || '打分失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('打分失败:', error);
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		});
	} finally {
		uni.hideLoading();
	}
}
	
	// 打分子函数
const mark = (item) => {
	selectedItem.value = item;
	scoreValue.value = '';
	commentValue.value = '';
	show.value = true;
}
	
	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}
	
	// 下拉刷新
	onPullDownRefresh(() => {
		getSalaryData(currentMonthStr.value);
	})
	
	onLoad(() => {
	getBarHeight();
	initCurrentDate();
	// 初始化调用时必传本月参数
	getSalaryData(currentMonthStr.value);
})
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 100%;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.screenBox {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 22rpx;
		box-sizing: border-box;
		margin-bottom: 20rpx;

		.tabBox {
			display: flex;
			align-items: center;
			justify-content: center;

			.tabLi {
				font-size: 29.49rpx;
				font-weight: 400;
				color: #3F3F3F;
				position: relative;

				text {
					margin-left: 9rpx;
				}
			}

			.tabLiA {
				font-weight: 500;
				font-size: 29.49rpx;
				color: #000000;
			}

			.tabLiA::after {
				content: "";
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				bottom: -10rpx;
				flex: 1;
				width: 61.54rpx;
				height: 6.41rpx;
				border-radius: 3.21rpx 3.21rpx 3.21rpx 3.21rpx;
				background: linear-gradient(-90deg, #feaf38, #f98434);
			}
		}

		.screenTime {
			height: 55rpx;
			border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
			background: #ffffff;
			color: #f79f31;
			font-weight: 400;
			font-size: 25.64rpx;
			padding: 0 15rpx;
			box-sizing: border-box;
			margin-left: 10rpx;
			display: flex;
			align-items: center;

			image {
				width: 13.46rpx;
				height: 8.33rpx;
				display: block;
				margin-left: 20rpx;
			}

			.screenTimeName {
				display: flex;
				align-items: center;

				image {
					width: 25.64rpx;
					height: 25.64rpx;
					display: block;
					margin-right: 7rpx;
					margin-left: 0;
				}
			}
		}


	}

	.contBox {
		padding: 0 22rpx;
		box-sizing: border-box;
		padding-bottom: env(safe-area-inset-bottom);
		
		.loading,
		.empty {
			text-align: center;
			padding: 60rpx 0;
			color: #999;
			font-size: 28rpx;
		}

		// padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);
		.contList {
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			padding: 34rpx 24rpx;
			box-sizing: border-box;
			margin-bottom: 22rpx;
			display: flex;
			align-items: center;

			.contTop {
				display: flex;
				align-items: center;
				justify-content: space-between;
				flex: 1;

				.contPerson {
					display: flex;
					align-items: center;

					.contPhoto {
					  width: 93.55rpx;
					  height: 93.55rpx;
					  background: #f8c79a; /* 背景色作为头像加载前的占位 */
					  border-radius: 50%;
					  overflow: hidden; /* 关键：隐藏图片超出圆形的部分 */
					  image {
					    width: 100%;
					    height: 100%;
					    object-fit: cover; /* 保持图片比例，避免拉伸变形 */
					  }
					}

					.contTopName {
						font-weight: 500;
						font-size: 33.33rpx;
						color: #000000;
						margin-left: 17rpx;
					}
				}

				.contTopRight {
					width: 128.53rpx;
					height: 50rpx;
					border-radius: 27.56rpx 27.56rpx 27.56rpx 27.56rpx;
					background: #fd503e;
					font-size: 24.36rpx;
					font-weight: 400;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;

					text {
						font-size: 26.92rpx;
						font-weight: 400;
						color: #FFFFFF;
					}
				}
			}

			.contYdf {
			  width: 94rpx;
			  height: 94rpx;
			  background: #f8c79a;
			  border-radius: 50%;
			  overflow: hidden; /* 添加 */
			  image {
			    width: 100%;
			    height: 100%;
			    object-fit: cover; /* 添加 */
			    border-radius: 50%;
			  }
			}

			.contYdfRight {
				flex: 1;
				margin-left: 20rpx;

				.contYdfRightTop {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.contYdfRightName {
						font-weight: 500;
						font-size: 33.33rpx;
						color: #000000;
					}

					.contYdfRightNum {
						font-size: 24.36rpx;
						font-weight: 400;
						color: #FFFFFF;
						border-radius: 6.41rpx 6.41rpx 6.41rpx 6.41rpx;
						background: linear-gradient(90deg, #fd6702, #ffaa57);
						// padding: 8rpx 17rpx;
						// box-sizing: border-box;
						width: 81rpx;
						height: 39rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}

				.contYdfRightText {
					display: flex;
					align-items: center;
					margin-top: 19rpx;

					image {
						width: 28.21rpx;
						height: 24.36rpx;
					}

					.contYdfRightTextCont {
						font-size: 25.64rpx;
						font-weight: 400;
						color: #7F8494;
						margin-left: 10rpx;
						width: 480rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
			}
		}
	}
	.popupBox{
		width: 644rpx;
		border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
		background: #ffffff;
		box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #c0c0c03b;
		padding: 51rpx 43rpx;
		box-sizing: border-box;
		.popupTit{
			font-weight: 500;
			font-size: 33.33rpx;
			color: #1C2027;
			margin-bottom: 50rpx;
		}
		.popupLi{
			display: flex;
			align-items: center;
			margin-bottom: 31rpx;
			.popupName{
				font-weight: 500;
				font-size: 26.92rpx;
				color: #1C2027;
				margin-right: 27rpx;
			}
			.popupInpt{
				width: 264.1rpx;
				height: 76.92rpx;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #f4f6f991;
				padding: 0 17rpx;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border: 1px solid #e3e6ed;
				.popupInptText{
					font-size: 24.36rpx;
					font-weight: 400;
					color: #1D1D1D;
				}
			}
			.popupTip{
				font-weight: 500;
				font-size: 26.92rpx;
				color: #FF2A2A;
				margin-left: 23rpx;
			}
			.popupTextarea{
				flex: 1;
				height: 311rpx;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #f4f6f991;
				padding: 27rpx 18rpx;
				box-sizing: border-box;
				border: 1px solid #e3e6ed;
				textarea{
					width: 100%;
					height: 100%;
					font-size: 24.36rpx;
					text-align: left;
					font-weight: 400;
					color: #7F8494 100%;
				}
			}
		}
	}
	
	.popupBtn{
		width: 435.9rpx;
		height: 83.33rpx;
		border-radius: 41.67rpx 41.67rpx 41.67rpx 41.67rpx;
		background: linear-gradient(90deg, #feaf38,#f98434);
		box-shadow: 0 3.85rpx 4.49rpx 0 #f984344d;
		font-size: 32.05rpx;
		font-weight: 400;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 69rpx auto 0;
	}
</style>